/*
 * Copyright (c) 2019.  鼎捷软件股份有限公司.All rights reserved.
 */

package com.digiwin.dap.middleware.service.impl;

import com.digiwin.dap.middleware.entity.BaseEntityWithId;
import com.digiwin.dap.middleware.exception.BusinessException;
import com.digiwin.dap.middleware.repository.BaseEntityWithIdRepository;
import com.digiwin.dap.middleware.service.EntityWithIdManagerService;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * 表操作服务基类，提供基于id为不可重复索引的表基本操作
 */
public abstract class BaseEntityWithIdManagerService<T extends BaseEntityWithId> extends BaseEntityManagerService<T> implements EntityWithIdManagerService<T> {


    /**
     * 派生类必须返回dao存来操作数据
     * @return jpa对象
     */
    @Override
    protected abstract BaseEntityWithIdRepository getRepository();

    @PersistenceContext
    EntityManager entityManager;

    /**
     * 根据tenantSid,id获取sid
     *
     * @param id
     * @return
     */
    @Override
    public long getSidById(String id) {
        String sql = String.format("SELECT  SID FROM %s WHERE ID = '%s' LIMIT 1", this.getMappingTableName(), id);
        List resultList = entityManager.createNativeQuery(sql).getResultList();
        if (resultList.size() == 0) {
            return 0;
        }
        return Long.valueOf(resultList.get(0).toString());
    }

    /**
     * 根据实体Id查询实体
     *
     * @param id 实体Id
     * @return 实体对象
     */
    @Override
    public T findById(String id) {
        return (T) getRepository().findById(id);
    }

    /**
     * 根据实体Id删除实体
     *
     * @param id 实体Id
     */
    @Override
    public void deleteById(String id) {
        getRepository().deleteById(id);
    }

    /**
     * 根据id判断是否存在
     *
     * @param id
     * @return
     */
    @Override
    public boolean existsById(String id) {
        return this.getRepository().existsById(id);
    }

    /**
     * 根据用户Id 启用
     *
     * @param id Id
     */
    @Override
    public void enable(String id) {
        BaseEntityWithId data = this.getRepository().findById(id);
        if (data != null) {
            data.setDisabled(false);
            this.getRepository().save(data);
        } else {
            throw new BusinessException("数据已经被删除.id:" + id);
        }
    }

    /**
     * 根据用户Id 禁用
     *
     * @param id Id
     */
    @Override
    public void disable(String id) {
        BaseEntityWithId data = this.getRepository().findById(id);
        if (data != null) {
            data.setDisabled(true);
            this.getRepository().save(data);
        } else {
            throw new BusinessException("数据已经被删除.id:" + id);
        }
    }

}
